﻿using System;
using System.Threading.Tasks;
using System.Windows.Input;
using Acr.UserDialogs;
using Cashbook.Models;
using Cashbook.Services;
using Cashbook.Views;
using Xamarin.Forms;

namespace Cashbook.ViewModels
{
	public class EditStatementVM : AbstractViewModel
	{
		private BillsDataAccess _billsService;
		private StatementsDataAccess _statementsService;

		public ObservableRangeCollection<Statement> Statements { get; set; }
		
		private INavigation _navigation;

		public Command LoadBillCommand { get; set; }
		public ICommand SaveCommand { get; private set; }
		public ICommand DeleteCommand { get; private set; }
        public ICommand SaveAndEndCommand { get; private set; }
		public ICommand DepositCommand { get; private set; }
		public ICommand BalanceCommand { get; private set; }
		public ICommand FinishCommand { get; private set; }


		protected IUserDialogs _dalogs { get; }



		Statement _statement;
		public Statement Statement
		{
			get { return this._statement; }
			set
			{
				if (this._statement == value)
					return;

				this._statement = value;
				this.OnPropertyChanged();
			}
		}

		BillVM _bill;
		public BillVM Bill
		{
			get { return this._bill; }
			set
			{
				if (this._bill == value)
					return;

				this._bill = value;
				this.OnPropertyChanged();
			}
		}

		string _title;
		public string Title
		{
			get { return this._title; }
			set
			{
				if (this._title == value)
					return;

				this._title = value;
				this.OnPropertyChanged();
			}
		}

		

		


		public EditStatementVM(BillVM bill, INavigation navigation, IUserDialogs dialogs) : base(dialogs)
        {
			_navigation = navigation;
			Bill = bill;
			Title = "添加结算单";

			_billsService = new BillsDataAccess();
            _statementsService = new StatementsDataAccess();

            Statements = new ObservableRangeCollection<Statement>();
			Statement = new Statement();           

			LoadBillCommand = new Command(async () => await ExecuteLoadBillCommand());
			SaveCommand = new Command(async () => await ExecuteSaveCommand());

			DeleteCommand = new Command<Statement>(async (model) => await ExecuteDeleteCommand(model));
            SaveAndEndCommand = new Command(async () => await ExecuteSaveAndEndCommand());

            DepositCommand = new Command( () => { Statement.Title = "定金";});
			BalanceCommand = new Command(() => { Statement.Title = "尾款"; });
			FinishCommand = new Command(() => { Statement.Title = "结算"; });


			
		}

        async Task ExecuteSaveAndEndCommand()
        {
			// Bill bill = new Bill();
			if (string.IsNullOrEmpty(Statement.Title))
			{

				await this.Dialogs.AlertAsync("请输入项目主题", "错误", "关闭");
				return;
			}


			if (Statement.Amount <= 0)
			{
				await this.Dialogs.AlertAsync("请输入金额必须大于0", "错误", "关闭");
				return;
			}
			Statement.BillId = Bill.Id;
			Statement.AddedDate = DateTime.Now;

			await _statementsService.SaveStatementAsync(Statement);

			//  await ExecuteLoadBillCommand();
			Statements.Insert(0, Statement);

            var bill = await _billsService.GetBillAsync(Bill.Id);
            bill.IsPayed = true;
            await _billsService.SaveBillAsync(bill);

            await _navigation.PushAsync(new BillPage());

        }

        async Task ExecuteLoadBillCommand()
		{
			

			try
			{
				Statements.Clear();
                var items = await _statementsService.GetStatementsAsync(Bill.Id);
				Statements.ReplaceRange(items);
				
				//Bill = await _billsService.GetBillAsync(BillId);

			}
			catch (Exception ex)
			{
				// Debug.WriteLine(ex);
				await this.Dialogs.AlertAsync("数据加载失败." + ex.Message, "错误", "确定");
			}
		
			
		}


		async Task ExecuteSaveCommand()
		{
           // Bill bill = new Bill();
            if (string.IsNullOrEmpty(Statement.Title))
			{

				await this.Dialogs.AlertAsync("请输入项目主题", "错误", "关闭");
				return;
			}


			if (Statement.Amount <= 0)
			{
				await this.Dialogs.AlertAsync("请输入金额必须大于0", "错误", "关闭");
				return;
			}
            Statement.BillId = Bill.Id;
            Statement.AddedDate = DateTime.Now;
           
            await _statementsService.SaveStatementAsync(Statement);

          //  await ExecuteLoadBillCommand();
            Statements.Insert(0,Statement);

            Statement = new Statement();

			//if (Bill.IsPayed)
			//	await _navigation.PushAsync(new BillIsPayedPage());
			//else
			//{
			//	await _navigation.PushAsync(new BillPage());
			//}
		}

		async Task ExecuteDeleteCommand(Statement model)
		{
			var result = await this.Dialogs.ConfirmAsync("您确定要删除当前所选结算单吗，此操作不可恢复？", "删除结算单", "确定", "取消");

			if (result)
			{
				
                var isDelete = await _statementsService.DeleteStatementAsync(model);
				if (isDelete > 0)
				{
					Statements.Remove(model);					
				}
			}

		}
	}
}
